from django.db import models

from ._base import BaseORM


class Rights(BaseORM):
    # id = models.IntegerField(verbose_name="编号", primary_key=True)
    title = models.CharField(verbose_name="权限名称", max_length=20)
    code = models.CharField(verbose_name="权限标识", max_length=30, null=True, blank=True)
    kind = models.CharField(verbose_name="权限类型", max_length=30)
    url = models.CharField(verbose_name="路径地址", null=True, blank=True, max_length=50)
    icon_sign = models.CharField(verbose_name="图标", max_length=128, null=True, blank=True)
    is_enabled = models.BooleanField(verbose_name="权限是否可用 0-禁止 1-可用", default=True)
    sort = models.IntegerField(verbose_name="显示排序", default=0)
    open_type = models.CharField(verbose_name="打开方式", max_length=128, null=True, blank=True, default="_iframe")
    remark = models.CharField(verbose_name="备注", max_length=255, null=True, blank=True)

    pid = models.ForeignKey(verbose_name="父类编号", to='self', on_delete=models.CASCADE, blank=True, null=True)

    class Meta:
        db_table = 'ums_rights'

    def menu_json(self):
        """动态菜单"""
        type_map_dict = {"menu": 0, "menu-z": 1, "menu-bug": 2}  # 可以想象成0是目录,1是文件

        return {
            "id": self.id,
            "pid": self.pid_id if self.pid_id is not None else 0,
            "title": self.title,
            "type": type_map_dict[self.kind],  # 前端模版的菜单数据结构规定了字段名为type
            "href": self.url,  # 注意
            "icon": self.icon_sign,
            "sort": self.sort,
            "openType": self.open_type or "_iframe",
            "remark": self.remark
        }

    def json(self):
        """对象的信息"""
        return {
            "id": self.id,
            "name": self.title,  # 注意,权限树形表格显示名字那一列必须叫作name,否则名字左侧那个展开收缩的箭头图标不会显示
            "code": self.code,
            "kind": self.kind,
            "url": self.url,
            "icon_sign": self.icon_sign,
            "is_enabled": self.is_enabled,
            "sort": self.sort,
            "open_type": self.open_type,
            "pid": self.pid_id,
            "remark": self.remark,
            "is_deleted": self.is_deleted,
            "children": [],
        }

    def json_tree(self):
        """上级权限在表单中的下拉框展示的是树 layui第三方组件combotree拿到该数据后会自动构建树"""
        return {
            "id": self.id,
            "name": self.title,  # 注意
            "pid": self.pid_id,
        }

    def json_power_tree(self):
        """这个用于在给角色分配权限时,先展示权限树!"""
        return {
            "id": self.id,
            "title": self.title,
            "pid": self.pid_id,
            "sort": self.sort,
            "spread": True,  # 这样展示的权限树就是默认展开的!
            "children": [],
        }
